<?php

namespace App\Http\Controllers;

use App\Http\Models\Customer;
use App\Http\Models\User;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @param  Request $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		if ($request->has('limit')) {
			$items = Customer::paginate($request->input('limit'));
		} else {
			$items = Customer::all();
		}

		return $this->table($items);
	}
	/**
	 * Display a listing of the resource.
	 *
	 * @param  Request $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function register(Request $request)
	{
		$user = new User;
		$user->id = $request->input('id');
		$user->name = $request->input('name');
		$user->password = $request->input('password');
		$user->role = 0;
		$user->save();

		$customer = new Customer;
		$customer->id = $request->input('id');
		$customer->phone = $request->input('phone');
		$customer->email = $request->input('email');
		$customer->user_id = $user->id;
		$customer->birth_date = $request->input('birth_date');
		$customer->integral = 0;
		return $customer->save()?
			$this->success('') : $this->failed('注册失败');
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param    \Illuminate\Http\Request  $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$model = new Customer;
		foreach ($request->toArray() as $key => $value) {
			if (in_array($key, $model->getFillable())) {
				$model[$key] = $value;
			}
		}
		return $model->save() ?
			$this->success('') : $this->failed('添加失败');
	}

	/**
	 * Display the specified resource.
	 *
	 * @param    int  $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function show($id)
	{
		return $this->success(Customer::find($id));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param    \Illuminate\Http\Request  $request
	 * @param    int  $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, $id)
	{
		$model = Customer::find($id);
		foreach ($request->toArray() as $key => $value) {
			if (in_array($key, $model->getFillable())) {
				$model[$key] = $value;
			}
		}
		return $model->update()  ? $this->success('') : $this->failed('更新失败');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param    int  $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function destroy($id)
	{
		return Customer::where('id', $id)->delete() ? $this->success('') : $this->failed('删除失败');

	}
}
